<?php
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance()->setFallbackAutoloader(true);
set_include_path(get_include_path() . ';' . realpath('../library'));

//header('HTTP/1.1 500 Internale error');
//exit;

// logger
$writer = new Zend_Log_Writer_Stream('upload.log');
$logger = new Zend_Log($writer);

try {
	$logger->info(var_export($_POST, true));
	$logger->info(var_export($_FILES, true));
	
	$uploadifyAdapter = new MyZendX_File_Transfer_Adapter_Uploadify();
	$adapter = $uploadifyAdapter->getBackendAdapter();
	//var_dump($adapter);
	$result = $adapter->receive();
	
	if ( $result === true ) {
		$fileinfo = $adapter->getFileInfo();
		$logger->info(var_export($result, true));
		$logger->info(var_export($fileinfo, true));

		$files = array();
		foreach( $fileinfo as $file ) {
			$files['name'] = $file['name'];
			if ( isset($_POST['previewWidth']) || isset($_POST['previewHeight']) ) {
				$files['preview'] = '<img src="/gfx/uploads/' . $file['name'] . '" width="200" />';
			}
		}
		
		header('Content-Type: application/json');
		echo Zend_Json::encode(array('uploaded' => $files));
	}
	else {
		header('Content-Type: application/json');
		echo Zend_Json::encode(array('errors' => $adapter->getMessages()));
	}
	
}
catch(Exception $e) {
	$logger->crit($e);
}